package com.tdam2011.grupo05.processor;

import java.io.UnsupportedEncodingException;

import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;

import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;

import com.tdam2011.grupo05.database.manager.DataManager;
import com.tdam2011.grupo05.entities.message.MessageWeb;
import com.tdam2011.grupo05.entities.message.MessageWeb.State;
import com.tdam2011.grupo05.entities.thread.ThreadWeb;
import com.tdam2011.grupo05.services.constant.MessageConstant;
import com.tdam2011.grupo05.services.constant.ServiceResult;
import com.tdam2011.grupo05.utils.parser.XMLParser;
import com.tdam2011.grupo05.utils.parser.XMLParser.Entry;

public class SendMessageProcessor implements Processor {

	private final static String TAG = "SendMessageProcessor";
	private MessageWeb mWeb;
	private ThreadWeb mThread;
	private final String mUser;
	private final String mPass;
	private ResultReceiver mReceiver;
	private final DataManager mManager;

	public SendMessageProcessor(DataManager manager, String user, String pass,
			ResultReceiver receiver) {
		mManager = manager;
		mReceiver = receiver;
		mUser = user;
		mPass = pass;
	}

	public void setMessageToSend(MessageWeb message, ThreadWeb thread) {
		mWeb = message;
		mThread = thread;
	}

	public void sendMessageLate() {
		Log.d(TAG, "delivery late=" + mWeb);
		mWeb.setResult(MessageConstant.NO_RESULT);
		mWeb.setState(State.UNSENDED);
		long id = mManager.saveMessage(mWeb);
		mWeb.setId(id);
		Log.d(TAG, "delivery late saved=" + mWeb);

	}

	@Override
	public StringEntity handleRequest() throws UnsupportedEncodingException {
		Log.d(TAG, "handleRequest: " + mWeb);

		mWeb.setResult(MessageConstant.NO_RESULT);
		mWeb.setState(State.UNSENDED);
		if (mWeb.getId() == 0) {
			// new message
			long id = mManager.saveMessage(mWeb);
			mWeb.setId(id);

		} else {
			// re send message
			mManager.updateMessage(mWeb);
		}

		final StringEntity se = new StringEntity("" + "<action id=\""
				+ mWeb.getId() + "\" name=\"send-message\">"
				+ "<action-detail>" + "<auth username=\"" + mUser + "\" key=\""
				+ mPass + "\">" + "</auth><message to=\""
				+ mThread.getUser().getName() + "\"><![CDATA[ "
				+ mWeb.getText() + "]]>"
				+ "</message></action-detail></action>", HTTP.UTF_8);

		se.setContentType("text/xml");

		return se;
	}

	@Override
	public void handleResponse(final Entry response, final String result) {
		Log.d(TAG, "handleResponse message " + result);
		Bundle data = new Bundle();
		data.putLong(MessageConstant.TIMESTAMP, mWeb.getTimestamp().getTime());

		if (response == null) {
			mWeb.setResult("error sended, null response");
			mWeb.setState(State.UNSENDED);
			data.putLong(MessageConstant.TIMESTAMP, mWeb.getTimestamp()
					.getTime());
			mReceiver.send(ServiceResult.MESSAGE_SENDED_FAIL, data);
		} else if (Integer.parseInt(response.getId()) == mWeb.getId()) {

			mWeb.setResult(response.getType());

			if (mWeb.getResult().equals(XMLParser.ERROR_RESULT)) {
				mWeb.setResult(MessageConstant.RESULT_ACTION + " "
						+ MessageConstant.DETAIL_ERROR);
				mWeb.setState(State.ERROR);
				data.putString(MessageConstant.RESULT_ACTION,
						response.getDetail());
				mReceiver.send(ServiceResult.MESSAGE_SENDED_FAIL, data);

			} else {
				mWeb.setState(State.SENDED);
				mReceiver.send(ServiceResult.MESSAGE_SENDED_OK, data);
			}

		} else {
			Log.e(TAG, "!= id");
			mWeb.setState(State.ERROR);

		}
		mManager.updateMessage(mWeb);
	}

	@Override
	public void cancelRequest() {
		mWeb.setState(State.CANCELED);
		mWeb.setResult("canceled");
		mManager.updateMessage(mWeb);
	}
}
